<template>
  <div class="user-manage-container">
    <!-- 搜索区域 -->
    <a-card class="search-card">
      <a-row :gutter="16">
        <a-col :span="20">
          <a-form :model="queryReq" layout="horizontal">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item field="username" label="用户">
                  <a-input
                    v-model="queryReq.username"
                    placeholder="请输入用户名"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item field="realName" label="姓名">
                  <a-input
                    v-model="queryReq.realName"
                    placeholder="请输入姓名"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item field="gender" label="性别">
                  <a-select
                    v-model="queryReq.gender"
                    allow-clear
                    placeholder="请选择性别"
                  >
                    <a-option :value="0">男</a-option>
                    <a-option :value="1">女</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item field="status" label="状态">
                  <a-select
                    v-model="queryReq.status"
                    allow-clear
                    placeholder="请选择状态"
                  >
                    <a-option :value="0">正常</a-option>
                    <a-option :value="1">封禁</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-col :span="4" class="action-buttons">
          <a-space>
            <a-button type="primary" @click="pageData">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <!-- 表格区域 -->
    <a-card class="table-card">
      <template #title>
        <div class="card-title">
          <icon-user />
          <span>用户列表</span>
          <a-tag>{{ pagination.total || 0 }}位用户</a-tag>
        </div>
      </template>
      <a-table
        bordered
        row-key="id"
        :columns="filteredColumns"
        :data="data.userList"
        :loading="loading"
        :pagination="pagination"
        @page-change="handlePageNumberChange"
        @page-size-change="handlePageSizeChange"
        :stripe="true"
      >
        <template #columns-setting>
          <a-tooltip content="列设置">
            <a-button size="small" shape="circle">
              <icon-settings />
            </a-button>
          </a-tooltip>
        </template>
        <template #Username="{ record }">
          <a-link>{{ record.username }}</a-link>
        </template>
        <template #Gender="{ record }">
          <a-tag :color="record.gender === 0 ? 'blue' : 'purple'">
            {{ record.gender === 0 ? '男' : '女' }}
          </a-tag>
        </template>
        <template #Roles="{ record }">
          <a-space wrap>
            <a-tag
              v-for="(item, index) in record.roles"
              :key="index"
              color="arcoblue"
            >
              {{ item }}
            </a-tag>
          </a-space>
        </template>
        <template #Status="{ record }">
          <a-tag :color="record.status === 0 ? 'green' : 'red'">
            {{ record.status === 0 ? '正常' : '封禁' }}
          </a-tag>
        </template>
        <template #Online="{ record }">
          <a-badge
            :status="record.online ? 'success' : 'error'"
            :text="record.online ? '在线' : '离线'"
          />
        </template>
        <template #Controls="{ record }">
          <a-space>
            <a-tooltip content="强制下线">
              <a-button
                type="text"
                size="small"
                :disabled="!record.online"
                @click="handleKick(record)"
              >
                <template #icon>
                  <icon-poweroff />
                </template>
              </a-button>
            </a-tooltip>
            <template v-if="record.status === 0">
              <a-popconfirm
                content="确定要封禁该用户吗？"
                position="left"
                @ok="handleDisable(record)"
              >
                <a-button type="text" status="danger" size="small">
                  <template #icon>
                    <icon-lock />
                  </template>
                  封禁
                </a-button>
              </a-popconfirm>
            </template>
            <a-button
              v-else
              type="text"
              status="success"
              size="small"
              @click="handleEnable(record)"
            >
              <template #icon>
                <icon-unlock />
              </template>
              解封
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
  <a-modal
    v-model:visible="roleVisible"
    :mask-closable="false"
    width="320px"
    title="赋权"
    @ok="handleOk"
  >
    <a-form-item label="角色">
      <a-select
        v-model="roleUser.roleIds"
        multiple
        allow-search
        allow-clear
        placeholder="请选择角色"
        :options="roleOptions"
      ></a-select>
    </a-form-item>
  </a-modal>
</template>

<script setup lang="ts">
import { Message, PaginationProps } from '@arco-design/web-vue';
import {
  Paging,
  SysRoleResponse,
  SysRoleService,
  SysUserRequest,
  SysUserResponse,
  SysUserService,
  UpdateUserRoleRequest
} from '@/api/gen-api';
import { onMounted, reactive, ref, unref, h, computed } from 'vue';
import columns from '@/views/sys/user/data.d';
import { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import {
  IconSearch,
  IconRefresh,
  IconUser,
  IconPoweroff,
  IconLock,
  IconUnlock,
  IconSettings
} from '@arco-design/web-vue/es/icon';

const paging: Paging = reactive({
  pageNum: 1,
  pageSize: 10
});

const handlePageSizeChange = (pageSize: number) => {
  paging.pageSize = pageSize;
  pageData();
};

const handlePageNumberChange = (pageNumber: number) => {
  paging.pageNum = pageNumber;
  pageData();
};

const loading = ref(false);
const queryReq = ref<SysUserRequest>({
  username: '',
  realName: '',
  gender: null,
  email: '',
  mobile: '',
  status: null
});
const data = reactive({
  userList: [] as SysUserResponse[]
});
const pagination = reactive<PaginationProps>({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100],
  showJumper: true,
  size: 'medium'
});

// 过滤掉含有"头像"的列
const filteredColumns = computed(() => {
  return columns.filter(
    column => !column.title.includes('头像') && column.dataIndex !== 'avatar'
  );
});

/**
 * 查询数据
 */
const pageData = async () => {
  loading.value = true;
  await SysUserService.page(paging, unref(queryReq))
    .then(res => {
      const result = res.result;
      data.userList = result.records;
      pagination.total = result.totalRow;
      pagination.current = paging.pageNum;
      pagination.pageSize = paging.pageSize;
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleDisable = (record: SysRoleResponse) => {
  SysUserService.disable(record.id).then(() => {
    Message.success({
      content: '用户封禁成功',
      icon: () => h(IconLock)
    });
    pageData();
  });
};

const handleEnable = (record: SysRoleResponse) => {
  SysUserService.enable(record.id).then(() => {
    Message.success({
      content: '用户解封成功',
      icon: () => h(IconUnlock)
    });
    pageData();
  });
};

const handleKick = (record: SysRoleResponse) => {
  SysUserService.kick(record.id).then(res => {
    if (res.result) {
      Message.success({
        content: '用户已强制下线',
        icon: () => h(IconPoweroff)
      });
      pageData();
    }
  });
};

/**
 * 重置查询条件
 */
const reset = () => {
  queryReq.value = {
    username: '',
    realName: '',
    gender: null,
    email: '',
    mobile: '',
    status: null
  };
  paging.pageNum = 1;
  pageData();
};

// 赋权弹窗
const roleVisible = ref(false);
const roleUser = ref<UpdateUserRoleRequest>({
  userId: 0,
  roleIds: []
});
/**
 * 赋权操作
 */
const handleOk = () => {
  SysRoleService.updateUserRole(roleUser.value).then(res => {
    if (res.result) {
      Message.success('赋权成功');
      roleVisible.value = false;
      pageData();
    }
  });
};
const roleOptions = ref<SelectOptionData[]>();
const getAllRole = () => {
  SysRoleService.list().then(res => {
    if (res.result) {
      roleOptions.value = res.result.map(item => {
        return {
          label: item.remark,
          value: item.id
        };
      });
    }
  });
};

const handleEditRole = (record: SysUserResponse) => {
  roleVisible.value = true;
  getAllRole();
  roleUser.value.userId = record.id;
};

onMounted(() => {
  pageData();
});
</script>

<style scoped lang="less">
.user-manage-container {
  .search-card {
    margin-bottom: 16px;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);

    :deep(.arco-card-body) {
      padding: 16px 20px;
    }

    .action-buttons {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      height: 100%;
    }
  }

  .table-card {
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);

    .card-title {
      display: flex;
      align-items: center;
      gap: 8px;

      .arco-icon {
        color: #2759cd;
        font-size: 18px;
      }

      span {
        font-size: 16px;
        font-weight: 500;
      }

      .arco-tag {
        margin-left: 8px;
      }
    }

    :deep(.arco-table) {
      .arco-table-th {
        background-color: var(--color-fill-2);
        font-weight: 500;
      }

      .arco-table-tr:hover {
        .arco-table-td {
          background-color: var(--color-fill-1);
        }
      }
    }
  }

  :deep(.arco-form-item-label) {
    font-weight: 500;
  }

  :deep(.arco-btn) {
    border-radius: 4px;

    &.arco-btn-primary {
      background-color: #2759cd;
      border-color: #2759cd;

      &:hover {
        background-color: #1a3a8f;
        border-color: #1a3a8f;
      }
    }
  }

  :deep(.arco-badge) {
    &-status-dot-success {
      background-color: rgb(var(--success-6));
    }

    &-status-dot-error {
      background-color: rgb(var(--danger-6));
    }

    &-status-text {
      font-size: 13px;
    }
  }

  :deep(.arco-tag) {
    border-radius: 3px;
  }

  :deep(.arco-pagination) {
    margin-top: 16px;
  }
}
</style>
